package com.itheima.reggie.task;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.service.DishService;
import com.itheima.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;

import java.io.File;
import java.time.LocalDateTime;

@Configuration
public class DeleteImgTask {

    @Value("${reggie.path}")
    private String imgPath;

    @Autowired
    private DishService dishService;

    @Autowired
    private SetmealService setmealService;
    // https://blog.csdn.net/sunnyzyq/article/details/98597252
    // cron表达式: 设置什么时间执行这个任务
    // * * * * * *
    // A B C D E F
    // A: 秒   */5 * * * * *
    // B: 分   0 */5 * * * *
    // C: 时   0 0 */5 * * *
    // D: 日
    // E: 月
    // F: 周
    @Scheduled(cron = "0 0 */1 * * *")
    public void deleteImg(){
        System.out.println("定时任务: "+LocalDateTime.now());
        File file = new File(imgPath);
        // 获取指定文件夹下所有的文件
        File[] files = file.listFiles();
        for (File f : files) {
            if (f.isDirectory()){
                System.out.println("文件夹: "+f.getName());
            }else {
                System.out.println("文件: "+f.getName());
                // 查询菜品表
                LambdaQueryWrapper<Dish> wrapper1 = new LambdaQueryWrapper<>();
                wrapper1.eq(Dish::getImage,f.getName());
                int count1 = dishService.count(wrapper1);
                // 查询套餐表
                LambdaQueryWrapper<Setmeal> wrapper2 = new LambdaQueryWrapper<>();
                wrapper2.eq(Setmeal::getImage,f.getName());
                int count2 = setmealService.count(wrapper2);
                if (count1==0 && count2==0){
                    f.delete();
                }
            }
        }
    }

}